package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional  //涉及到两张及以上的表增删改时，要使用事务注解
    public void insert(DishDTO dishDTO) {
        Dish dish = new Dish();

        //属性对拷，将已有的参数拷贝到dish中
        BeanUtils.copyProperties(dishDTO, dish);

        //插入菜品信息
        dishMapper.insert(dish);

        //2.构造菜品口味列表数据，将其存入dish_flavor表中
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();

        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            //遍历口味信息，并赋值对应id
            dishFlavorList.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });

            //2.2 调用Mapper保存方法，批量插入口味列表数据
            dishFlavorMapper.insertBatch(dishFlavorList);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //1.调用分页插件，设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //2.调用Mapper方法，强转成Page<DishVO>
        Page<DishVO> dishVOPage = dishMapper.list(dishPageQueryDTO);

        //封装成PageResult对象并返回数据
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     */
    @Override
    public void status(Integer status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.status(dish);
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional //同时操作多张表
    public void deleteBatch(List<Long> ids) {
        //1.遍历利率表中的id,判断是否有起售的菜品
        ids.forEach(id->{
            //根据id查询菜品
            Dish  dish = dishMapper.getDishById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //起售中的菜品不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //2.根据菜品id查询setmeal_dish表，判断是否被套餐关联，被关联的不能删除
        Integer countMealIds = setmealDishMapper.getSetmealDishByDishIds(ids);
        if (countMealIds != null && countMealIds > 0){
            //被套餐关联的菜品不能被删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.根据id删除菜品
        dishMapper.deleteByIds(ids);

        //4.根据id删除菜品口味
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    @Transactional //开启事务
    public void update(DishDTO dishDTO) {
        //1.根据id查询菜品信息，用于回显
        //dishFlavorMapper.getDishFlavorByDishId(dishDTO.getId());

        //1.创建出菜品对象
        Dish dish = new Dish();
        log.info("dish：{}",dish);

        //2.属性对拷
        BeanUtils.copyProperties(dishDTO, dish);
        log.info("================dish：{}==============",dish);

        //2.1 获取菜品id并放入集合中
        ArrayList<Long> dishId = new ArrayList<>();
        dishId.add(dish.getId());

        //3.先删除原来的口味信息，再插入传来的口味
        // 删除原有的口味数据
        dishFlavorMapper.deleteByDishIds(dishId);

        // 获取口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();

        //4.更新菜品信息
        dishMapper.update(dish);

        if (!flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            // 向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishDTO selectById(Long id) {
        //1.创建dishDto类
        DishDTO dishDTO = new DishDTO();
        //根据id查询菜品基本信息
        Dish dish = dishMapper.getDishById(id);
        //属性对拷
        BeanUtils.copyProperties(dish, dishDTO);

        //2.根据id查询菜品口味信息
        List<DishFlavor> dishFlavors= dishFlavorMapper.getDishFlavorByDishId(id);

        dishDTO.setFlavors(dishFlavors);
        return dishDTO;
    }



    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishes = dishMapper.getDishByCategoryId(dish);
        return dishes;
    }

    /**
     * C端-根据分类id查询菜品
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithCDishVO(Dish dish) {
        //1.构造DishVO集合对象
        List<DishVO> dishVOList = new ArrayList<>();

        //2.根据id查询菜品信息
        List<Dish> dishByCategoryId = dishMapper.getDishByCategoryId(dish);

        dishByCategoryId.forEach(d ->{
            //2.1 构造DishVO对象并将属性拷贝给该对象
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //3.根据id查询菜品口味信息
            List<DishFlavor> dishFlavors= dishFlavorMapper.getDishFlavorByDishId(d.getId());

            dishVO.setFlavors(dishFlavors);
            dishVOList.add(dishVO);
        });
        return dishVOList;
    }


}
